<!-- 签到功能使用示例 -->
<template>
  <div class="signin-example">
    <h3>签到功能使用示例</h3>
    
    <!-- 文件上传签到 -->
    <div class="file-signin">
      <h4>文件上传签到</h4>
      <input 
        type="file" 
        accept="image/*" 
        @change="handleFileUpload"
        ref="fileInput"
      />
      <button @click="signInWithFile" :disabled="!selectedFile">
        文件签到
      </button>
    </div>
    
    <!-- 摄像头签到 -->
    <div class="camera-signin">
      <h4>摄像头签到</h4>
      <video ref="video" autoplay muted playsinline></video>
      <canvas ref="canvas" style="display: none;"></canvas>
      <div class="camera-controls">
        <button @click="startCamera" :disabled="isCameraActive">
          开启摄像头
        </button>
        <button @click="capturePhoto" :disabled="!isCameraActive">
          拍照
        </button>
        <button @click="signInWithCamera" :disabled="!capturedImage">
          摄像头签到
        </button>
        <button @click="stopCamera" :disabled="!isCameraActive">
          关闭摄像头
        </button>
      </div>
      <div v-if="capturedImage" class="photo-preview">
        <img :src="capturedImage" alt="签到照片" />
      </div>
    </div>
    
    <!-- 签到结果 -->
    <div v-if="signinResult" class="signin-result">
      <h4>签到结果</h4>
      <p>状态: {{ signinResult.success ? '成功' : '失败' }}</p>
      <p v-if="signinResult.success">相似度: {{ signinResult.data }}%</p>
      <p>消息: {{ signinResult.message }}</p>
    </div>
  </div>
</template>

<script>
import { signinApiService, signinUtils } from '@/api/signin'

export default {
  name: 'SigninExample',
  data() {
    return {
      selectedFile: null,
      isCameraActive: false,
      capturedImage: null,
      cameraStream: null,
      signinResult: null
    }
  },
  methods: {
    // 处理文件上传
    handleFileUpload(event) {
      const file = event.target.files[0]
      if (file) {
        const validation = signinUtils.validateImageFile(file)
        if (validation.isValid) {
          this.selectedFile = file
          console.log('文件选择成功:', file.name, signinUtils.formatFileSize(file.size))
        } else {
          alert(validation.message)
          this.$refs.fileInput.value = ''
        }
      }
    },
    
    // 文件签到
    async signInWithFile() {
      if (!this.selectedFile) {
        alert('请先选择图片文件')
        return
      }
      
      try {
        // 压缩图片
        const compressedImage = await signinApiService.compressImage(this.selectedFile)
        
        const signinData = {
          image: compressedImage,
          userId: signinUtils.getCurrentUserId(),
          liveName: '示例直播'
        }
        
        this.signinResult = await signinApiService.signIn(signinData)
      } catch (error) {
        console.error('文件签到失败:', error)
        this.signinResult = {
          success: false,
          message: '签到失败: ' + error.message
        }
      }
    },
    
    // 开启摄像头
    async startCamera() {
      try {
        this.cameraStream = await navigator.mediaDevices.getUserMedia({
          video: { 
            width: { ideal: 640 },
            height: { ideal: 480 },
            facingMode: 'user'
          },
          audio: false
        })
        
        this.$refs.video.srcObject = this.cameraStream
        this.isCameraActive = true
        console.log('摄像头启动成功')
      } catch (error) {
        console.error('摄像头启动失败:', error)
        alert('摄像头启动失败: ' + error.message)
      }
    },
    
    // 拍照
    capturePhoto() {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      
      if (!video || !canvas) {
        alert('摄像头未准备好')
        return
      }
      
      try {
        const context = canvas.getContext('2d')
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        
        context.drawImage(video, 0, 0, canvas.width, canvas.height)
        this.capturedImage = canvas.toDataURL('image/jpeg', 0.8)
        
        console.log('拍照成功')
      } catch (error) {
        console.error('拍照失败:', error)
        alert('拍照失败')
      }
    },
    
    // 摄像头签到
    async signInWithCamera() {
      if (!this.capturedImage) {
        alert('请先拍照')
        return
      }
      
      try {
        // 将base64图片转换为Blob
        const imageBlob = await signinApiService.dataURLtoBlob(this.capturedImage)
        
        // 压缩图片
        const compressedImage = await signinApiService.compressImage(imageBlob)
        
        const signinData = {
          image: compressedImage,
          userId: signinUtils.getCurrentUserId(),
          liveName: '示例直播'
        }
        
        this.signinResult = await signinApiService.signIn(signinData)
      } catch (error) {
        console.error('摄像头签到失败:', error)
        this.signinResult = {
          success: false,
          message: '签到失败: ' + error.message
        }
      }
    },
    
    // 关闭摄像头
    stopCamera() {
      if (this.cameraStream) {
        this.cameraStream.getTracks().forEach(track => track.stop())
        this.cameraStream = null
      }
      
      if (this.$refs.video) {
        this.$refs.video.srcObject = null
      }
      
      this.isCameraActive = false
      this.capturedImage = null
      console.log('摄像头已关闭')
    }
  },
  
  // 组件销毁时清理资源
  beforeUnmount() {
    this.stopCamera()
  }
}
</script>

<style scoped>
.signin-example {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.file-signin, .camera-signin {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.camera-controls {
  margin: 10px 0;
}

.camera-controls button {
  margin-right: 10px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.camera-controls button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.photo-preview {
  margin-top: 10px;
}

.photo-preview img {
  max-width: 200px;
  max-height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.signin-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

video {
  width: 100%;
  max-width: 400px;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>

